/**
 * 
 */
package org.xserver.runtime.jetty.command;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.xserver.annotation.PerformanceLog;
import org.xserver.annotation.VisitorLog;
import org.xserver.core.command.ICommand;

/**
 * @author jkonopka
 * 
 */
public class WebAppContextInitializeCommand implements ICommand {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5601397597984168337L;

	/**
	 * 
	 */
	private static final String CONTEXT_PATH = "/";

	/**
	 * 
	 */
	private static final String WEBAPPS_XSERVER_WAR = "./webapps/xserver.war";

	private final Server server;

	/**
	 * @param server {@link Server}
	 */
	public WebAppContextInitializeCommand(final Server server) {
		this.server = server;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jserver.command.ICommand#execute()
	 */
	@Override
	@VisitorLog
	@PerformanceLog
	public void execute() throws Exception {

		if (existPath(WEBAPPS_XSERVER_WAR)) {
			final WebAppContext wac = new WebAppContext();
			wac.setContextPath(CONTEXT_PATH);
			wac.setWar(WEBAPPS_XSERVER_WAR);
			server.setHandler(wac);
		}

		server.setStopAtShutdown(true);

	}

	/**
	 * @param warPath
	 * @return
	 */
	private boolean existPath(final String warPath) {
		return new File(FilenameUtils.concat(new File("").getAbsolutePath(), warPath)).exists();
	}

}
